#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文献筛选程序 - 图形界面版本
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
import threading
import os
import sys
from pathlib import Path

# 导入现有的模块
from literature_filter import LiteratureFilter
from config import EASYSCHOLAR_API_KEY

class LiteratureFilterGUI:
    """文献筛选程序图形界面"""
    
    def __init__(self, root):
        self.root = root
        self.root.title("文献筛选程序 v1.0")
        self.root.geometry("800x900")
        
        # 获取屏幕尺寸并设置窗口位置
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_width = 800
        window_height = 900
        
        # 计算窗口位置（居中并向左偏移100像素，向上偏移20像素）
        x = (screen_width - window_width) // 2 - 100
        y = (screen_height - window_height) // 2 - 20
        
        # 确保坐标不为负数
        if x < 0:
            x = 0
        if y < 0:
            y = 0
            
        self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")
        self.root.resizable(True, True)
        
        # 设置图标（如果有的话）
        try:
            self.root.iconbitmap("icon.ico")
        except:
            pass
        
        # 初始化变量
        self.input_file = tk.StringVar()
        self.output_file = tk.StringVar()
        self.api_key = tk.StringVar(value=EASYSCHOLAR_API_KEY)
        self.show_stats = tk.BooleanVar(value=True)
        self.progress_var = tk.DoubleVar()
        self.status_var = tk.StringVar(value="就绪")
        
        # 筛选条件变量
        self.keep_sci_q1 = tk.BooleanVar(value=True)
        self.keep_sci_q2 = tk.BooleanVar(value=True)
        self.keep_sci_q3 = tk.BooleanVar(value=False)
        self.keep_sci_q4 = tk.BooleanVar(value=False)
        self.keep_cas_q1 = tk.BooleanVar(value=True)
        self.keep_cas_q2 = tk.BooleanVar(value=True)
        self.keep_cas_q3 = tk.BooleanVar(value=True)
        self.keep_cas_q4 = tk.BooleanVar(value=False)
        self.remove_unknown = tk.BooleanVar(value=False)
        
        # 创建界面
        self.create_widgets()
        
        # 初始化筛选器
        self.filter = None
        self.is_running = False
        
    def create_widgets(self):
        """创建界面组件"""
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        
        # 标题
        title_label = ttk.Label(main_frame, text="文献筛选程序", font=("Arial", 16, "bold"))
        title_label.grid(row=0, column=0, columnspan=3, pady=(0, 20))
        
        # 文件选择区域
        file_frame = ttk.LabelFrame(main_frame, text="文件设置", padding="10")
        file_frame.grid(row=1, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
        file_frame.columnconfigure(1, weight=1)
        
        # 输入文件
        ttk.Label(file_frame, text="输入文件:").grid(row=0, column=0, sticky=tk.W, pady=5)
        ttk.Entry(file_frame, textvariable=self.input_file, width=50).grid(row=0, column=1, sticky=(tk.W, tk.E), padx=(5, 5), pady=5)
        ttk.Button(file_frame, text="浏览", command=self.browse_input_file).grid(row=0, column=2, pady=5)
        
        # 输出文件
        ttk.Label(file_frame, text="输出文件:").grid(row=1, column=0, sticky=tk.W, pady=5)
        ttk.Entry(file_frame, textvariable=self.output_file, width=50).grid(row=1, column=1, sticky=(tk.W, tk.E), padx=(5, 5), pady=5)
        ttk.Button(file_frame, text="浏览", command=self.browse_output_file).grid(row=1, column=2, pady=5)
        
        # API设置区域
        api_frame = ttk.LabelFrame(main_frame, text="API设置", padding="10")
        api_frame.grid(row=2, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
        api_frame.columnconfigure(1, weight=1)
        
        ttk.Label(api_frame, text="EasyScholar密钥:").grid(row=0, column=0, sticky=tk.W, pady=5)
        api_entry = ttk.Entry(api_frame, textvariable=self.api_key, width=50, show="*")
        api_entry.grid(row=0, column=1, sticky=(tk.W, tk.E), padx=(5, 5), pady=5)
        
        # 显示/隐藏API密钥按钮
        self.show_api_var = tk.BooleanVar()
        ttk.Checkbutton(api_frame, text="显示密钥", variable=self.show_api_var, 
                       command=lambda: api_entry.config(show="" if self.show_api_var.get() else "*")).grid(row=0, column=2, pady=5)
        
        # 选项设置区域
        options_frame = ttk.LabelFrame(main_frame, text="选项设置", padding="10")
        options_frame.grid(row=3, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
        
        ttk.Checkbutton(options_frame, text="显示统计信息", variable=self.show_stats).grid(row=0, column=0, sticky=tk.W, pady=5)
        ttk.Checkbutton(options_frame, text="删除无法获取分区信息的文献", variable=self.remove_unknown).grid(row=0, column=1, sticky=tk.W, pady=5)
        
        # 筛选条件选择区域
        filter_frame = ttk.LabelFrame(main_frame, text="筛选条件", padding="10")
        filter_frame.grid(row=4, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
        filter_frame.columnconfigure(1, weight=1)
        filter_frame.columnconfigure(3, weight=1)
        
        # SCI分区选择
        ttk.Label(filter_frame, text="保留SCI分区:", font=("Arial", 10, "bold")).grid(row=0, column=0, sticky=tk.W, pady=5)
        sci_frame = ttk.Frame(filter_frame)
        sci_frame.grid(row=1, column=0, columnspan=2, sticky=tk.W, pady=5)
        ttk.Checkbutton(sci_frame, text="Q1", variable=self.keep_sci_q1).grid(row=0, column=0, padx=(0, 10))
        ttk.Checkbutton(sci_frame, text="Q2", variable=self.keep_sci_q2).grid(row=0, column=1, padx=(0, 10))
        ttk.Checkbutton(sci_frame, text="Q3", variable=self.keep_sci_q3).grid(row=0, column=2, padx=(0, 10))
        ttk.Checkbutton(sci_frame, text="Q4", variable=self.keep_sci_q4).grid(row=0, column=3, padx=(0, 10))
        
        # 中科院分区选择
        ttk.Label(filter_frame, text="保留中科院分区:", font=("Arial", 10, "bold")).grid(row=0, column=2, sticky=tk.W, pady=5)
        cas_frame = ttk.Frame(filter_frame)
        cas_frame.grid(row=1, column=2, columnspan=2, sticky=tk.W, pady=5)
        ttk.Checkbutton(cas_frame, text="Q1", variable=self.keep_cas_q1).grid(row=0, column=0, padx=(0, 10))
        ttk.Checkbutton(cas_frame, text="Q2", variable=self.keep_cas_q2).grid(row=0, column=1, padx=(0, 10))
        ttk.Checkbutton(cas_frame, text="Q3", variable=self.keep_cas_q3).grid(row=0, column=2, padx=(0, 10))
        ttk.Checkbutton(cas_frame, text="Q4", variable=self.keep_cas_q4).grid(row=0, column=3, padx=(0, 10))
        
        # 筛选规则说明
        rules_frame = ttk.LabelFrame(main_frame, text="筛选规则说明", padding="10")
        rules_frame.grid(row=5, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
        
        rules_text = "• 满足任一保留条件的文献将被保留\n• 两个条件都不满足的文献将被删除\n• 无法获取分区信息的文献根据设置决定是否删除"
        ttk.Label(rules_frame, text=rules_text, justify=tk.LEFT).grid(row=0, column=0, sticky=tk.W)
        
        # 控制按钮区域
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=6, column=0, columnspan=3, pady=(0, 10))
        
        self.start_button = ttk.Button(button_frame, text="开始筛选", command=self.start_filtering)
        self.start_button.grid(row=0, column=0, padx=(0, 10))
        
        self.stop_button = ttk.Button(button_frame, text="停止", command=self.stop_filtering, state=tk.DISABLED)
        self.stop_button.grid(row=0, column=1, padx=(0, 10))
        
        ttk.Button(button_frame, text="清空日志", command=self.clear_log).grid(row=0, column=2, padx=(0, 10))
        
        ttk.Button(button_frame, text="退出", command=self.root.quit).grid(row=0, column=3)
        
        # 进度条
        progress_frame = ttk.Frame(main_frame)
        progress_frame.grid(row=7, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
        progress_frame.columnconfigure(0, weight=1)
        
        ttk.Label(progress_frame, textvariable=self.status_var).grid(row=0, column=0, sticky=tk.W)
        self.progress_bar = ttk.Progressbar(progress_frame, variable=self.progress_var, maximum=100)
        self.progress_bar.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(5, 0))
        
        # 日志区域
        log_frame = ttk.LabelFrame(main_frame, text="运行日志", padding="10")
        log_frame.grid(row=8, column=0, columnspan=3, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
        log_frame.columnconfigure(0, weight=1)
        log_frame.rowconfigure(0, weight=1)
        main_frame.rowconfigure(8, weight=1)
        
        self.log_text = scrolledtext.ScrolledText(log_frame, height=15, width=80)
        self.log_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 初始日志
        self.log("文献筛选程序已启动")
        self.log("请选择输入文件并设置EasyScholar密钥")
        
    def browse_input_file(self):
        """浏览输入文件"""
        filename = filedialog.askopenfilename(
            title="选择RIS文件",
            filetypes=[("RIS files", "*.ris"), ("All files", "*.*")]
        )
        if filename:
            # 标准化路径
            normalized_filename = str(Path(filename).resolve())
            self.input_file.set(normalized_filename)
            # 自动生成输出文件名
            input_path = Path(normalized_filename)
            output_path = input_path.parent / f"{input_path.stem}_filtered{input_path.suffix}"
            self.output_file.set(str(output_path))
            self.log(f"已选择输入文件: {normalized_filename}")
            
    def browse_output_file(self):
        """浏览输出文件"""
        filename = filedialog.asksaveasfilename(
            title="保存筛选结果",
            defaultextension=".ris",
            filetypes=[("RIS files", "*.ris"), ("All files", "*.*")]
        )
        if filename:
            # 标准化路径
            normalized_filename = str(Path(filename).resolve())
            self.output_file.set(normalized_filename)
            self.log(f"已设置输出文件: {normalized_filename}")
            
    def log(self, message):
        """添加日志信息"""
        self.log_text.insert(tk.END, f"{message}\n")
        self.log_text.see(tk.END)
        self.root.update_idletasks()
        
    def clear_log(self):
        """清空日志"""
        self.log_text.delete(1.0, tk.END)
        self.log("日志已清空")
        
    def update_status(self, message, progress=None):
        """更新状态和进度"""
        self.status_var.set(message)
        if progress is not None:
            self.progress_var.set(progress)
        self.root.update_idletasks()
        
    def start_filtering(self):
        """开始筛选"""
        if self.is_running:
            return
            
        # 验证输入
        if not self.input_file.get():
            messagebox.showerror("错误", "请选择输入文件")
            return
            
        if not os.path.exists(self.input_file.get()):
            messagebox.showerror("错误", "输入文件不存在")
            return
            
        if not self.api_key.get():
            messagebox.showerror("错误", "请设置EasyScholar密钥")
            return
            
        # 设置输出文件
        if not self.output_file.get():
            input_path = Path(self.input_file.get())
            output_path = input_path.parent / f"{input_path.stem}_filtered{input_path.suffix}"
            self.output_file.set(str(output_path.resolve()))
            
        # 在新线程中运行筛选
        self.is_running = True
        self.start_button.config(state=tk.DISABLED)
        self.stop_button.config(state=tk.NORMAL)
        
        thread = threading.Thread(target=self.run_filtering)
        thread.daemon = True
        thread.start()
        
    def stop_filtering(self):
        """停止筛选"""
        self.is_running = False
        self.log("正在停止筛选...")
        
    def run_filtering(self):
        """运行筛选过程"""
        try:
            self.log("开始文献筛选...")
            
            # 获取筛选条件
            keep_sci_quartiles = []
            if self.keep_sci_q1.get(): keep_sci_quartiles.append('Q1')
            if self.keep_sci_q2.get(): keep_sci_quartiles.append('Q2')
            if self.keep_sci_q3.get(): keep_sci_quartiles.append('Q3')
            if self.keep_sci_q4.get(): keep_sci_quartiles.append('Q4')
            
            keep_cas_quartiles = []
            if self.keep_cas_q1.get(): keep_cas_quartiles.append('Q1')
            if self.keep_cas_q2.get(): keep_cas_quartiles.append('Q2')
            if self.keep_cas_q3.get(): keep_cas_quartiles.append('Q3')
            if self.keep_cas_q4.get(): keep_cas_quartiles.append('Q4')
            
            # 创建筛选器
            self.filter = LiteratureFilter(
                api_key=self.api_key.get(),
                keep_sci_quartiles=keep_sci_quartiles,
                keep_cas_quartiles=keep_cas_quartiles,
                remove_unknown=self.remove_unknown.get()
            )
            
            # 定义进度回调函数
            def progress_callback(progress, message):
                if not self.is_running:  # 检查是否被停止
                    raise Exception("用户停止筛选")
                self.update_status(message, progress)
                self.log(message)
            
            # 运行筛选
            original_count, filtered_count, filtered_entries = self.filter.filter_literature(
                self.input_file.get(), 
                self.output_file.get(),
                progress_callback
            )
            
            # 显示结果
            deleted_count = original_count - filtered_count
            self.log(f"筛选完成!")
            self.log(f"原始文献数量: {original_count}")
            self.log(f"筛选后数量: {filtered_count}")
            self.log(f"删除数量: {deleted_count}")
            self.log(f"保留比例: {(filtered_count/original_count*100):.1f}%")
            self.log(f"结果已保存到: {self.output_file.get()}")
            
            if self.show_stats.get():
                self.log("\n=== 统计信息 ===")
                stats = self.filter.get_filtering_stats(filtered_entries)
                for key, value in stats.items():
                    self.log(f"{key}: {value}")
            
            messagebox.showinfo("完成", f"筛选完成!\n原始: {original_count} 篇\n筛选后: {filtered_count} 篇\n删除: {deleted_count} 篇")
            
        except Exception as e:
            if "用户停止筛选" in str(e):
                self.log("筛选已停止")
            else:
                self.log(f"筛选过程中出错: {e}")
                messagebox.showerror("错误", f"筛选过程中出错:\n{str(e)}")
            
        finally:
            self.is_running = False
            self.start_button.config(state=tk.NORMAL)
            self.stop_button.config(state=tk.DISABLED)
            self.update_status("就绪", 0)
            
    def on_closing(self):
        """程序关闭时的处理"""
        if self.is_running:
            if messagebox.askokcancel("退出", "筛选正在进行中，确定要退出吗？"):
                self.is_running = False
                self.root.destroy()
        else:
            self.root.destroy()

def main():
    """主函数"""
    root = tk.Tk()
    app = LiteratureFilterGUI(root)
    
    # 设置关闭事件
    root.protocol("WM_DELETE_WINDOW", app.on_closing)
    
    # 启动主循环
    root.mainloop()

if __name__ == "__main__":
    main() 